<?php declare(strict_types=1);


namespace app\model;

class User extends Base {

    protected $name = 'user';

    // 设置字段信息
    protected $schema = [
        'user_id'     => 'int',
        'account'   =>'string',
        'password'  =>'string',
        'introduction'=>'string',
        'avatar'=>'string',
        'status'=>'int',
        'expire_at' => 'datetime',
        'create_at' => 'datetime',
        'update_at' => 'datetime',
        'delete_at' => 'datetime'
    ];

    // User Token
    public function token(){
        return $this->hasOne('UserToken','user_id','user_id');
    }


    // Get Token By Login Info
    public function getUserByLogin(array $postData) : ?User{
        $result = $this->with('token')->where('account','=',trim($postData['account']))->where('password','=',$postData['password'])->find();
        return $result;
    }

    // Get Token By User ID
    public function getTokenByUserId(string $id) : ?UserToken  {
        $token =  $this->where('user_id','=',$id)->find();
        return $token;
    }

    // Get User By User ID
    public function getUserByUserId(int $userId) : ?User
    {
        $user = $this->where('user_id','=',$userId)->find();
        return $user;
    }


    public function getUserByAccount(string $account): ?User{
        $user = $this->where('account','=',$account)->find();
        return $user;
    }


    public function getUserList($page = 1,$pageSize = 15){
        $user = $this->page($page,$pageSize)->select();
        return $user;
    }

    public function getUserCount():int {
        $count = $this->count('user_id');
        return $count;
    }


    public function del(int $userId) : bool {
        $user =  $this->where('user_id','=',$userId)->find();
        if($user){
            $result = $user->delete();
            return $result >=1 ? true : false;
        }
        return false;
    }


    public function updateUser(array $userData): bool {
        $result = self::where('account','=',$userData['account'])->save($userData);
        return $result >=1 ? true : false;
    }

    public function createUser(array $userData): bool {
        $result = self::save($userData);
        return $result >=1 ? true : false;
    }
}

 
